import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
import {
  ajaxAddPowerUser,
  ajaxModifyPowerUser
} from '../../../api/power'
const util = require('../../../utils/util.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    params: {},
    // 添加还是修改
    type: 'add'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    app.getPrevPageData(this).then(async (res) => {
      let data = res.data || {};
      this.setData({
        type: options.type,
        params: Object.assign({}, data, {
          ifCancel: data.ifCancel == 'Y',
          ifAudit: data.ifAudit == 'Y'
        })
      })
    })
  },
  onChange({
    currentTarget: {
      dataset: {
        name
      }
    }
  }) {
    this.setData({
      [`params.${name}`]: !this.data.params[name]
    })
  },
  async submit() {
    let params = this.data.params;
    let types = [];
    // 核销
    if (params.ifCancel) {
      types.push(2);
    }
    // 退款
    if (params.ifAudit) {
      types.push(3);
    }
    if (!types.length) {
      Toast('至少要选择一个权限')
      return;
    }
    Toast.loading({
      message: '正在处理',
      forbidClick: true,
      duration: 0
    });
    try {
      await (this.data.type == 'add' ? ajaxAddPowerUser({
        userId: params.k1UserId,
        types: types
      }) : ajaxModifyPowerUser({
        userId: params.k1UserId,
        ifCancel: params.ifCancel ? 'Y' : 'N',
        ifAudit: params.ifAudit ? 'Y' : 'N'
      }))
      await app.myNextTick()
      Toast.clear();
      Toast({
        type: 'success',
        forbidClick: true,
        message: '操作成功',
        duration: 1000,
        onClose: () => {
          // 返回到列表
          let pages = getCurrentPages() || [],
            index = pages.findIndex(item => item.route == 'pages/permissionManage/index');
          wx.navigateBack({
            delta: pages.length - (index + 1),
          })
        }
      })
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || '失败');
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  }
})